﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;

namespace QDWK.Class
{
    public class CZjzy
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly RemoteSysInfo _remoteSysInfo;
        private readonly ILogger<CZjzy> _logger;

        public CZjzy(RemoteSysInfo remoteSysInfo, IHttpClientFactory httpClientFactory, ILogger<CZjzy> logger)
        {
            _remoteSysInfo = remoteSysInfo;
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }       

        public async Task<string> CallRestServiceWithSoapAsync(string serviceUrl, List<VendorStock> payload)
        {
            try
            {
                var pushData = new
                {
                    vendorStock = payload
                };
                string jsonPayload = JsonConvert.SerializeObject(pushData);
                var client = _httpClientFactory.CreateClient();

                Console.WriteLine(jsonPayload);
                // Set Basic Authentication header
                var authValue = new AuthenticationHeaderValue(
                    "Basic",
                    Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_remoteSysInfo.UserName}:{_remoteSysInfo.Password}")));

                client.DefaultRequestHeaders.Authorization = authValue;
                client.DefaultRequestHeaders.Accept.Clear();
                // Set content type for SOAP
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // Create the request content            
                var content = new StringContent(jsonPayload, Encoding.UTF8, "text/xml");

                // Send the request
                HttpResponseMessage response = await client.PostAsync(_remoteSysInfo.Url, content).ConfigureAwait(false);

                // Check for success
                if (!response.IsSuccessStatusCode)
                {
                    string errorBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    _logger.LogError($"Error: {response.StatusCode} - {errorBody}");
                    return errorBody;
                }

                return "success";
                
            }
            catch (Exception ex)
            {
                _logger.LogError($"{ex}");
                return ex.ToString(); ;            
            }
        }
    }
}
